package second.codeTop.package2;

/**
 * @ClassName LC5
 * @description:
 * @author: 荣燊
 * @create: 2022-04-06 16:12
 **/
public class LC5 {
    public static void main(String[] args) {
        String s = "cbbd";
        System.out.println(longestPalindrome(s));
    }

    //最长回文子串
    //动态规划
    public static String longestPalindrome(String s) {
        int len = s.length();
        if (len == 1) {
            return s;
        }
        // 记录最长回文子串的大小，还有开始位置就可以了
        int maxLen = 1; //只有两个字符时，那么肯定是第一个
        int begin = 0;
        char[] chars = s.toCharArray();
        boolean[][] dp = new boolean[len][len];
        for (int i=0; i<len; i++) {
            dp[i][i] = true;
        }
        //开始进行动态规划
        for (int l=1; l<len; l++) {
            for (int i=0; i<len; i++) {
                int j = i + l;
                //越界判断
                if (j >= len) {
                    break;
                }
                if (chars[i] != chars[j]) {
                    dp[i][j] = false;
                } else {
                    if (l < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i+1][j-1];
                    }
                }
                if (dp[i][j] && maxLen < j-i+1) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin+maxLen);
    }
}
